const WebSocket = require('ws');
const port = 9000
const ws = new WebSocket('ws://localhost:' + port);
let interval;

id = 0;

const audio_params = {
	rate: 8000,
	codec: "L16",
	ms: 100,
}

ws.on('open', function open() {
	rpc = {
		jsonrpc: "2.0",
		id: id++,
		method: "start",
		params: audio_params
	}

	data = JSON.stringify(rpc);
	console.log("Sending: ", data);
	ws.send(data);
});

ws.on('message', function message(data, isBinary) {
	console.log('received: isBinary=%s type=%s length=%d', isBinary, typeof(data), data.length);

	if (isBinary) {

	} else {
		rpc = JSON.parse(data)
		console.log(rpc);

		if (rpc.result?.code == 200) {
			interval = setInterval(send_audio, audio_params.ms);
		}
	}
});

function send_audio() {
	const array = new Int16Array(audio_params.rate / 1000 * audio_params.ms)
	ws.send(array); // send as binary	
}

ws.on('close', function close() {
	console.log("closed");
	process.exit();
});

process.on("SIGINT", function () { // Ctrl+C
	clearInterval(interval);
	const rpc = {
		jsonrpc: "2.0",
		id: id++,
		method: "stop",
		params: {
			cause: "NORMAL_CLEARING"
		}
	}
	const data = JSON.stringify(rpc);
	console.log("sending: ", data);
	ws.send(data);
	process.exit();
});
